package cn.hchaojie.camp.playground;

import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class BallGame extends Application {
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage primaryStage) throws Exception {
		BorderPane box = new BorderPane();
		
		MainPane pane = new MainPane();
		
		HBox hbox = new HBox(10);
		hbox.setAlignment(Pos.CENTER);
		Button btnAdd = new Button("+");
		btnAdd.setOnAction(e -> pane.add());
		
		Button btnRemove = new Button("-");
		hbox.getChildren().addAll(btnAdd, btnRemove);
		
		box.setCenter(pane);
		box.setBottom(hbox);
		
		Scene scene = new Scene(box, 400, 300);
		primaryStage.setScene(scene);
		primaryStage.show();
	}
	
	class MainPane extends Pane {
		private Timeline timeline;
		
		public MainPane() {
			timeline = new Timeline(new KeyFrame(Duration.millis(50), e -> {
				move();
			}));
			timeline.setCycleCount(Timeline.INDEFINITE);
			timeline.setRate(10);
			timeline.play();
		}

		public void add() {
			Color c = new Color(Math.random(), Math.random(), Math.random(), Math.random());

			Ball ball = new Ball(100, 100, 20, c);
			
			getChildren().add(ball);
		}
		
		public void move() {
			for (Node child : this.getChildren()) {
				Ball c = (Ball) child;
				
				if (c.getCenterX() < c.getRadius() 
						|| c.getCenterX() > getWidth() - c.getRadius()) {
					c.dx = -c.dx;
				}

				if (c.getCenterY() < c.getRadius()
						|| c.getCenterY() > getHeight() - c.getRadius()) {
					
					c.dy = -c.dy;
				} 
				
				c.setCenterX(c.getCenterX() + c.dx);
				c.setCenterY(c.getCenterY() + c.dy);
			}
		}
	}
	
	class Ball extends Circle {
		private double dx = 1;
		private double dy = 1;
		
		public Ball(double x, double y, double radius, Color c) {
			super(x, y, radius);
			
			setFill(c);
		}
	}
}
